from fastapi import APIRouter, Query,UploadFile
from pandas.plotting import table
from tortoise.expressions import Q

from app.controllers.appointment.space import appointment_space_controller
from app.controllers.saas.consumables import consumables_controller
from app.controllers.saas.consumables_use import consumables_use_controller
from app.controllers.system.user import user_controller
from app.core.ctx import CTX_USER_ID
from app.core.dependency import DependCustomerAuth
from app.models import Buckling, CustomerUser, Goods, BucklingDetail, Consumables, Cases
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.saas import *
from app.settings.config import settings
mini_saas_consumables_use_router = APIRouter()
model_name = "耗材使用明细"


@mini_saas_consumables_use_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_settings_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description=f"{model_name}名称"),
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
):
    q = Q()
    search_consumables_ids = []
    user_id = CTX_USER_ID.get()
    user = await user_controller.get(user_id)
    if user.space_id:
        q &= Q(space_id=user.space_id)
    if name:
        search_consumables = await Consumables.filter(name__contains=name).values("id")
        search_consumables_ids = {one['id'] for one in search_consumables}  # 获取所有的 user_id
        q &= Q(consumables_id__in=search_consumables_ids)

    if start_time and end_time:
        q &= Q(created_at__range=[start_time, end_time])
    elif start_time:
        q &= Q(created_at__gte=start_time)
    elif end_time:
        q &= Q(created_at__lte=end_time)

    consumables_objs = await consumables_controller.do_all()
    total, data = await consumables_use_controller.do_list(page=page, page_size=page_size, search=q)
    cases_ids = {data_item['cases_id'] for data_item in data}  # 获取所有的 user_id
    cases = await Cases.filter(id__in=cases_ids)
    cases_dict = {cases_item.id: cases_item for cases_item in cases}
    space_objs = await appointment_space_controller.level_list()


    for item in data:
        cases_one = cases_dict.get(item['cases_id'])
        # buckling_detail_one = buckling_detail_dict.get(item['buckling_detail_id'])
        customer = await CustomerUser.filter(id=cases_one.user_id).first().values()
        # goods = await Goods.filter(id=buckling_one.goods_id).first().values()

        item["consumables_name"] = consumables_objs[item["consumables_id"]]
        # item["order_id"] = buckling_one.order_id
        item["user_name"] = customer["name"]
        item["space_name"] = space_objs[cases_one.space_id]

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@mini_saas_consumables_use_router.get("/get", summary=f"查看{model_name}")
async def do_settings_get(
        data_id: int = Query(..., description="ID"),
):
    data = await consumables_use_controller.do_detail(data_id=data_id)
    return Success(data=data)

@mini_saas_consumables_use_router.post("/create", summary=f"创建{model_name}")
async def do_settings_create(
        data_in: ConsumablesUseCreate,
):
    await consumables_use_controller.do_create(obj_in=data_in)
    return Success(msg="创建成功")

@mini_saas_consumables_use_router.post("/update", summary=f"更新{model_name}")
async def do_settings_update(
        data_in: ConsumablesUseUpdate,
):
    await consumables_use_controller.do_update(obj_in=data_in)
    return Success(msg="更新成功")

@mini_saas_consumables_use_router.delete("/delete", summary=f"删除{model_name}")
async def do_settings_delete(
        data_id: int = Query(..., description="ID"),
):
    await consumables_use_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")
